package org.nf.web.servlet.param;

import org.nf.web.servlet.MethodArgumentResolver;
import org.nf.web.servlet.ServletApi;

import jakarta.servlet.http.Part;
import java.lang.reflect.Parameter;

/**
 * @author wangl
 * @date 2023/4/13
 * 负责解析Part类型的参数
 */
public class RequestPartMethodArgumentResolver implements MethodArgumentResolver {

    @Override
    public boolean supports(Parameter parameter) {
        Class<?> type = parameter.getType().isArray() ?
                parameter.getType().getComponentType() : parameter.getType();
        return Part.class.isAssignableFrom(type);

    }

    @Override
    public Object resolve(Parameter parameter, ServletApi servletApi) throws Exception{
        Part[] parts = servletApi.request().getParts().stream()
                    .filter(part -> part.getSubmittedFileName() != null
                            && !"".equals(part.getSubmittedFileName()))
                    .toArray(Part[]::new);
        return (parameter.getType().isArray()) ? parts :
                parts.length > 0 ? parts[0] : null;
    }
}
